#include "klib.h"
#include <stdarg.h>

#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)

char stkbuf[10];
int8_t stp=0;

void int2str(uint32_t num , int h) {
  uint8_t n;
  stp = 0;
  if(num == 0){
    stp = 1;
    stkbuf[0] = '0';
  }
  while (num){
    n = num % h;
    stkbuf[stp++] = n >= 10 ? (n - 10 + 'a') : (n + '0');
    num /=h;
    // stkbuf[stp++] = num % 10 + '0';
    // num /=10;
  }
}

// void int2strH(uint32_t num) {
//   uint8_t n;
//   stp = 0;
//   if(num == 0){
//     stp = 1;
//     stkbuf[0] = '0';
//   }
//   while (num){
//     n = num % 16;
//     stkbuf[stp++] = n >= 10 ? (n - 10 + 'a') : (n + '0');
//     num /=16;
//   }
// }

// void log(char* s) {
//   size_t len = strlen(s);
//   for (size_t i = 0; i < len; i++)
//     _putc(s[i]);
//   _putc('\n');
// }

char pbuf[1024];

int printf(const char *fmt, ...) {
  va_list ap;
  size_t len;

	va_start(ap, fmt);
	vsprintf(pbuf,fmt, ap);	
	va_end(ap);
  len = strlen(pbuf);

  for (size_t i = 0; i < len; i++)
    _putc(pbuf[i]);

	return 0;
}


int vsprintf(char *out, const char *fmt, va_list ap) {
	int ind = 0;
  int num ;
  char* str;
  char ch = '\0';
  memset(out,0,strlen(out));
	for(; *fmt != '\0'; fmt++) {
    if (*fmt != '%') {             //顺序查找判断，遇到%就推出，否则继续循环输出
      out[ind++]=(*fmt);            
      continue;       		
    }
		fmt++;
    switch (*fmt) {                                  //判断格式输出
      case 'd': 
        num = va_arg(ap, int);
        int2str(num,10);
        while(stp){
          stp--;
          out[ind++] = stkbuf[stp];
        }
        break;
      case 's': 
        str = va_arg(ap, char *);
        strcpy(out+ind,str);
        ind = ind + strlen(str);
        break;
      case 'c':
        // log("a char is here");
        ch = va_arg(ap, int);
        out[ind++] = ch;
        break;
      case 'p':
      case 'x':
        num = va_arg(ap, uint32_t);
        int2str(num,16);
        out[ind++] = '0';
        out[ind++] = 'x';
        while(stp){
          stp--;
          out[ind++] = stkbuf[stp];
        }
        break;
      default:
        out[ind++] = *fmt;
        break;
    }
	}
  out[ind] = '\0';
	return 0;
}


int sprintf(char *out, const char *fmt, ...) {

	va_list ap;

	va_start(ap, fmt);
	vsprintf(out,fmt,ap);	
	va_end(ap);

  return 0;
}

int snprintf(char *out, size_t n, const char *fmt, ...) {
  return 0;
}

#endif
